package com.ewhale.feitengguest.ui.user.mine;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.alipay.sdk.app.AuthTask;
import com.ewhale.feitengguest.R;
import com.ewhale.feitengguest.dto.AliAuthInfoDto;
import com.ewhale.feitengguest.dto.AuthInfoDto;
import com.ewhale.feitengguest.dto.AuthResult;
import com.ewhale.feitengguest.dto.LoginInfoDto;
import com.ewhale.feitengguest.dto.OriginDataDto;
import com.ewhale.feitengguest.presenter.user.mine.UserInfoPresenter;
import com.ewhale.feitengguest.utils.Contants;
import com.ewhale.feitengguest.utils.OrderInfoUtil;
import com.ewhale.feitengguest.utils.PickerUtils;
import com.ewhale.feitengguest.utils.PictureUtils;
import com.ewhale.feitengguest.utils.QiniuUtils;
import com.ewhale.feitengguest.view.user.mine.UserInfoView;
import com.ewhale.feitengguest.widget.InputNameDialog;
import com.luck.picture.lib.PictureSelector;
import com.orhanobut.hawk.Hawk;
import com.simga.library.activity.MBaseActivity;
import com.simga.library.http.JsonUtil;
import com.simga.library.utils.CheckUtil;
import com.simga.library.utils.CircleImageView;
import com.simga.library.utils.HawkKey;
import com.simga.library.utils.LogUtil;
import com.simga.library.utils.glide.GlideUtil;
import com.simga.library.widget.SelectPhotoDialog;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jiguang.share.android.api.AuthListener;
import cn.jiguang.share.android.api.JShareInterface;
import cn.jiguang.share.android.api.Platform;
import cn.jiguang.share.android.model.AccessTokenInfo;
import cn.jiguang.share.android.model.BaseResponseInfo;
import cn.jiguang.share.android.model.UserInfo;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class UserInfoActivity extends MBaseActivity<UserInfoPresenter> implements UserInfoView, EasyPermissions.PermissionCallbacks {
    @BindView(R.id.iv_avatar)
    CircleImageView mIvAvatar;
    @BindView(R.id.tv_nickname)
    TextView mTvNickname;
    @BindView(R.id.tv_realyname)
    TextView mTvRealyname;
    @BindView(R.id.tv_sex)
    TextView mTvSex;
    @BindView(R.id.tv_birthday)
    TextView mTvBirthday;
    @BindView(R.id.tv_wechat)
    TextView mTvWechat;
    @BindView(R.id.tv_alipay)
    TextView mTvAlipay;
    @BindView(R.id.tv_phone)
    TextView mTvPhone;
    @BindView(R.id.tv_auth)
    TextView mTvAuth;

    private LoginInfoDto mInfoDto;
    private InputNameDialog mInputNameDialog;
    private SelectPhotoDialog mPhotoDialog;
    private int chooseType = 1;
    private static final int REQUEST_CODE_PERMISSION_2 = 10002;
    private static final int REQUEST_CODE_CHOOSE_COMMENT_IMAGE = 1000;
    private static final int REQUEST_CODE_BINGD_ALIACCOUNT = 1001;
    private static final int SDK_AUTH_FLAG = 2;
    private AuthInfoDto authDto;

    public static void open(MBaseActivity context) {
        context.startActivity(null, UserInfoActivity.class);
    }

    @Override
    protected int getViewId() {
        return R.layout.activity_userinfo;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setTitle("我的资料");
        mInfoDto = Hawk.get(HawkKey.USER_LOGIN_INFO, null);
        if (mInfoDto != null) {
            GlideUtil.loadPicture(mInfoDto.getHeadPhoto(), mIvAvatar, R.drawable.default_image);
            mTvPhone.setText(mInfoDto.getPhone());
            mTvNickname.setText(mInfoDto.getNickName());
            if (mInfoDto.getSex() == 0) {
                mTvSex.setText("保密");
            } else if (mInfoDto.getSex() == 1) {
                mTvSex.setText("男");
            } else {
                mTvSex.setText("女");
            }
            mTvBirthday.setText(mInfoDto.getBirth());
            if (CheckUtil.isNull(mInfoDto.getAliAccount())) {
                mTvAlipay.setText("未绑定");
            } else {
                mTvAlipay.setText(mInfoDto.getAliAccount());
            }
            if (CheckUtil.isNull(mInfoDto.getWechatId())) {
                mTvWechat.setText("未绑定");
            } else {
                mTvWechat.setText("已绑定");
            }
            if (mInfoDto.getAuthStatus() == 0) {
                mTvAuth.setText("未认证");
            } else if (mInfoDto.getAuthStatus() == 1) {
                mTvAuth.setText("已认证");
            }
        }
    }

    @Override
    protected boolean isUseBaseTitleBar() {
        return true;
    }

    @Override
    protected void initListener() {
    }

    @Override
    public void showProLoading() {
        showLoading();
    }

    @Override
    public void dimissProLoading() {
        dismissLoading();
    }

    @Override
    public void showErrorMessage(int postCode, String code, String message) {
        showErrorMsg(code, message);
    }

    @OnClick({R.id.rl_avatar, R.id.rl_nickname, R.id.rl_realyname,
            R.id.rl_sex, R.id.rl_birthday, R.id.rl_wechat,
            R.id.rl_alipay, R.id.rl_phone, R.id.tv_reset_pwd, R.id.rl_auth})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_avatar:
                mPhotoDialog = new SelectPhotoDialog(mContext);
                mPhotoDialog.setOnClickItem(new SelectPhotoDialog.onClickItem() {
                    @Override
                    public void onOneClick() {
                        chooseType = 1;
                        requestPermissionsMain();
                    }

                    @Override
                    public void onTwoClick() {
                        chooseType = 2;
                        requestPermissionsMain();
                    }
                });
                mPhotoDialog.show();
                break;
            case R.id.rl_nickname:
                mInputNameDialog = new InputNameDialog(mContext, "请输入昵称");
                mInputNameDialog.setCommitCallBack(name -> presenter.resetNickName(name));
                mInputNameDialog.show();
                break;
            case R.id.rl_realyname:
                if (authDto.getStatus() == 2) {
                    return;
                }
                mInputNameDialog = new InputNameDialog(mContext, "请输入真实姓名");
                mInputNameDialog.setCommitCallBack(name -> presenter.resetName(name));
                mInputNameDialog.show();
                break;
            case R.id.rl_sex:
                PickerUtils.getInstance().pickerOption(mContext, "性别", new String[]{"男", "女"}, new PickerUtils.onCallBackOptions() {
                    @Override
                    public void onOptionPicked(int index, String item) {
                        presenter.resetSex((index + 1));
                    }
                });
                break;
            case R.id.rl_birthday:
                PickerUtils.getInstance().pickerYearMouth(mContext, "请选择出生日期", (year, month, day) -> presenter.resetBirthday(Integer.parseInt(year), Integer.parseInt(month)));
                break;
            case R.id.rl_wechat:
                if (CheckUtil.isNull(mInfoDto.getWechatId())) {
                    JShareInterface.authorize(Contants.weChat, mAuthListener);
                }
                break;
            case R.id.rl_alipay:
//                if (CheckUtil.isNull(mInfoDto.getAliId())) {
//                    presenter.getAliAuthInfo();
//                }
                if (authDto.getStatus() == 2) {
                    BindAliAccountActivity.open(mContext, authDto.getName(), REQUEST_CODE_BINGD_ALIACCOUNT);
                } else {
                    showToast("请完善实名认证");
                }
                break;
            case R.id.rl_phone:
                ResetPhoneFirstActivity.open(mContext, ResetPhoneFirstActivity.RESET_PHONE);
                break;
            case R.id.tv_reset_pwd:
                ResetPhoneFirstActivity.open(mContext, ResetPhoneFirstActivity.RESET_PASSWORD);
                break;
            case R.id.rl_auth:
                RNCertificationActivity.open(mContext);
                break;
        }
    }

    AuthListener mAuthListener = new AuthListener() {
        @Override
        public void onComplete(Platform platform, int action, BaseResponseInfo data) {
            LogUtil.e("LOGIN", "onComplete:" + platform + ",action:" + action + ",data:" + data);
            switch (action) {
                case Platform.ACTION_AUTHORIZING:
                    if (data instanceof AccessTokenInfo) {
                        String originData = data.getOriginData();
                        OriginDataDto dataDto = JsonUtil.fromJson(originData, OriginDataDto.class);//授权信息
                        String openid = platform.getName().equals(Contants.weChat) ? dataDto.getUnionid() : ((UserInfo) data).getOpenid();
                        presenter.bindThird(openid, 1);
                    }
                    break;
            }
        }

        @Override
        public void onError(Platform platform, int action, int errorCode, Throwable error) {
            LogUtil.e("LOGIN", "onError:" + platform + ",action:" + action + ",error:" + error);
            String toastMsg = null;
            switch (action) {
                case Platform.ACTION_AUTHORIZING:
                    toastMsg = "授权失败";
                    break;
                case Platform.ACTION_REMOVE_AUTHORIZING:
                    toastMsg = "删除授权失败";
                    break;
            }
            showToast(toastMsg);
        }

        @Override
        public void onCancel(Platform platform, int action) {
            String toastMsg = null;
            switch (action) {
                case Platform.ACTION_AUTHORIZING:
                    toastMsg = "取消授权";
                    break;
            }
            showToast(toastMsg);
        }
    };

    @AfterPermissionGranted(REQUEST_CODE_PERMISSION_2)
    private void requestPermissionsMain() {
        String[] perms = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(mContext, perms)) {
            if (chooseType == 1) {
                PictureUtils.openCameraRectangle(this, REQUEST_CODE_CHOOSE_COMMENT_IMAGE);
            } else {
                PictureUtils.openAluamOneRectangle(this, REQUEST_CODE_CHOOSE_COMMENT_IMAGE);
            }
        } else {
            EasyPermissions.requestPermissions(this, "申请获取相关权限",
                    REQUEST_CODE_PERMISSION_2, perms);
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        if (chooseType == 1) {
            PictureUtils.openCameraRectangle(this, REQUEST_CODE_CHOOSE_COMMENT_IMAGE);
        } else {
            PictureUtils.openAluamOneRectangle(this, REQUEST_CODE_CHOOSE_COMMENT_IMAGE);
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).setTitle("权限申请")
                    .setRationale("申请获取相关权限")
                    .setPositiveButton(getString(R.string.comfir))
                    .setNegativeButton(getString(R.string.cancle))
                    .build()
                    .show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == REQUEST_CODE_CHOOSE_COMMENT_IMAGE) {
            List<String> images = new ArrayList<>();
            images.add(PictureSelector.obtainMultipleResult(data).get(0).getCutPath());
            QiniuUtils.uploadImage(images, keys -> {
                presenter.resetHeadPhoto(keys.get(0));
                PictureUtils.clearCache(mContext);
            });
        } else if (requestCode == REQUEST_CODE_BINGD_ALIACCOUNT) {
            mInfoDto = Hawk.get(HawkKey.USER_LOGIN_INFO, null);
            mTvAlipay.setText(mInfoDto.getAliAccount());
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        presenter.loadAuthInfo();
    }

    @Override
    public void resetAvatar(String imageUrl) {
        if (mInfoDto != null) {
            mInfoDto.setHeadPhoto(imageUrl);
            GlideUtil.loadPicture(mInfoDto.getHeadPhoto(), mIvAvatar, R.drawable.default_image);
            Hawk.put(HawkKey.USER_AVATAR, imageUrl);
            Hawk.put(HawkKey.USER_LOGIN_INFO, mInfoDto);
        }
    }

    @Override
    public void resetName(String name) {
        if (mInfoDto != null) {
            mInfoDto.setName(name);
            mTvRealyname.setText(name);
            Hawk.put(HawkKey.USER_LOGIN_INFO, mInfoDto);
        }
    }

    @Override
    public void resetNickName(String nickname) {
        if (mInfoDto != null) {
            mInfoDto.setNickName(nickname);
            mTvNickname.setText(nickname);
            Hawk.put(HawkKey.USER_NICK_NAME, nickname);
            Hawk.put(HawkKey.USER_LOGIN_INFO, mInfoDto);
        }
    }

    @Override
    public void resetSex(int sex) {
        if (mInfoDto != null) {
            mInfoDto.setSex(sex);
            mTvSex.setText(sex == 1 ? "男" : "女");
            Hawk.put(HawkKey.USER_LOGIN_INFO, mInfoDto);
        }
    }

    @Override
    public void resetBirthday(String birthday) {
        if (mInfoDto != null) {
            mInfoDto.setBirth(birthday);
            mTvBirthday.setText(birthday);
            Hawk.put(HawkKey.USER_LOGIN_INFO, mInfoDto);
        }
    }

    @Override
    public void bindSuccess(Map<String, Object> params) {
        if ((int) params.get("type") == 1) {
            mTvWechat.setText("已绑定");
            mInfoDto.setWechatId((String) params.get("openid"));
        } else {
            mInfoDto.setAliId((String) params.get("openid"));
            mTvAlipay.setText("已绑定");
        }
        Hawk.put(HawkKey.USER_LOGIN_INFO, mInfoDto);
    }

    @Override
    public void handleInfo(AliAuthInfoDto result) {
        Map<String, String> authInfoMap = OrderInfoUtil.buildAuthInfoMap(result.getPid(), result.getAppId(), result.getTargetId(), false);
        String info = OrderInfoUtil.buildOrderParam(authInfoMap);
        String privateKey = result.getRsa2Private();
        String sign = OrderInfoUtil.getSign(authInfoMap, privateKey, false);
        final String authInfo = info + "&" + sign;
        LogUtil.e("JIA", "-----info : " + info);
        LogUtil.e("JIA", "-----sign : " + sign);
        Runnable authRunnable = () -> {
            // 构造AuthTask 对象
            AuthTask authTask = new AuthTask(UserInfoActivity.this);
            // 调用授权接口，获取授权结果
            Map<String, String> result1 = authTask.authV2(authInfo, true);
            for (String s : result1.keySet()) {
                System.out.println("key : " + s + " value : " + result1.get(s));
            }
            Message msg = new Message();
            msg.what = SDK_AUTH_FLAG;
            msg.obj = result1;
            mHandler.sendMessage(msg);
        };
        // 必须异步调用
        Thread authThread = new Thread(authRunnable);
        authThread.start();
    }

    @Override
    public void showAuthInfo(AuthInfoDto result) {
        authDto = result;
        Hawk.put(HawkKey.USER_AUTH_STATUS, result.getStatus());
        if (result.getStatus() == 2) {
            mTvAuth.setText("已认证");
            mInfoDto.setName(result.getName());
            Hawk.put(HawkKey.USER_LOGIN_INFO, mInfoDto);
            mTvRealyname.setText(result.getName());
        } else if (result.getStatus() == 1) {
            mTvRealyname.setText(mInfoDto.getName());
            mTvAuth.setText("审核失败");
        } else if (result.getStatus() == 0) {
            mTvRealyname.setText(mInfoDto.getName());
            mTvAuth.setText("审核中");
        } else if (result.getStatus() == -1) {
            mTvRealyname.setText(mInfoDto.getName());
            mTvAuth.setText("未认证");
        }
    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();
                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        LogUtil.e("JIA", "---授权成功---");
                        presenter.bindThird(authResult.getAlipayOpenId(), 2);
                    } else {
                        LogUtil.e("JIA", "---授权失败--- ： " + authResult.getAuthCode());
                    }
                    break;
                }
            }
        }
    };
}
